import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  Widget build(BuildContext context) => MaterialApp(
        title: '第04课 - 状态管理入门',
        theme: ThemeData(useMaterial3: true, colorSchemeSeed: Colors.green),
        home: const Lesson04Page(),
      );
}

class Lesson04Page extends StatefulWidget {
  const Lesson04Page({super.key});
  @override
  State<Lesson04Page> createState() => _Lesson04PageState();
}

class _Lesson04PageState extends State<Lesson04Page> {
  final Color _default = Colors.blue;
  Color _selected = Colors.blue;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('父子通信与状态提升')),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          children: [
            Container(
              height: 120,
              decoration: BoxDecoration(
                color: _selected.withOpacity(0.2),
                borderRadius: BorderRadius.circular(16),
                border: Border.all(color: _selected, width: 2),
              ),
              child: Center(
                child: Text('预览区域', style: TextStyle(color: _selected)),
              ),
            ),
            const SizedBox(height: 16),
            ColorPicker(
              colors: const [
                Colors.blue,
                Colors.red,
                Colors.green,
                Colors.orange,
                Colors.purple,
              ],
              selected: _selected,
              defaultColor: _default,
              onChanged: (c) => setState(() => _selected = c),
            ),
          ],
        ),
      ),
    );
  }
}

class ColorPicker extends StatelessWidget {
  final List<Color> colors;
  final Color selected;
  final Color defaultColor;
  final ValueChanged<Color> onChanged;
  const ColorPicker({
    super.key,
    required this.colors,
    required this.selected,
    required this.defaultColor,
    required this.onChanged,
  });

  String _nameOf(Color c) {
    if (c.value == Colors.blue.value) return '蓝色';
    if (c.value == Colors.red.value) return '红色';
    if (c.value == Colors.green.value) return '绿色';
    if (c.value == Colors.orange.value) return '橙色';
    if (c.value == Colors.purple.value) return '紫色';
    return '颜色';
  }

  @override
  Widget build(BuildContext context) {
    return Wrap(
      spacing: 12,
      children: colors.map((c) {
        final isSelected = c.value == selected.value;
        return ChoiceChip(
          label: Text(_nameOf(c)),
          selected: isSelected,
          onSelected: (sel) => onChanged(sel ? c : defaultColor),
          avatar: Icon(Icons.circle, color: c),
          showCheckmark: false,
        );
      }).toList(),
    );
  }
}